<template>
  <el-upload
    class="img-upload"
    ref="upload"
    action="http://www.coolcsm.xyz:8080/user/avatar"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-success="handleSuccess"
    :before-upload="beforeAvatarUpload"
    multiple
    :limit="1"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <el-button size="small" type="primary" >点击更换</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
</template>


<script>
  export default {
    name: 'ImgUpload',
    data () {
      return {
        fileList: [],
        url: ''
      }
    },
    methods: {
      handleRemove (file, fileList) {
      },
      handlePreview (file) {
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      beforeRemove (file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
       beforeAvatarUpload(file) {
      // 类型
      const isJPG = file.type === "image/jpeg";
      // 大小
      const isLt2M = file.size / 1024 / 1024 < 2;
      // 类型限制
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      // 大小限制
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
     },
      handleSuccess (response) {
        this.url = response
        this.$emit('onUpload')
        this.$message.warning('上传成功')
        this.fileList = []
      },
      clear () {
        this.$refs.upload.clearFiles()
      },

    }
  }
</script>

<style scoped>

</style>

